/*
 * @Author: 鱿鱼溪学院
 * @Date: 2025-04-23 01:12:18
 * @LastEditTime: 2025-04-28 23:10:38
 * @LastEditors: 鱿鱼溪学院
 * @Description:
 * @FilePath: \yyx_ser_ts\app\service\UserService.ts
 * Copyright 鱿鱼溪学院 by edu v1.0
 * 天道酬勤
 */
import { GetAdminException } from '../exception/HttpException'
import Admin from '../model/Admin'
import User from '../model/User'
import { adminInfo, userInfo } from '../types/custom'

class UserService {
  //获取管理员信息
  async getUserInfo({ id, username, phone, password }: userInfo) {
    const whereOpt = {}

    //短路运算，如果id存在才能执行后续操作，如果不存在，直接跳过
    id && Object.assign(whereOpt, { id })
    username && Object.assign(whereOpt, { username })
    phone && Object.assign(whereOpt, { phone })
    password && Object.assign(whereOpt, { password })

    const res = await User.findOne({
      attributes: ['id', 'username', 'phone', 'password'],
      where: whereOpt
    })

    return res ? res.dataValues : null
  }

  //添加用户
  async createUser(username: string, password: string, phone: string) {
    //todo:写入数据库
    //由于键值，名称一致，可以简写
    const res = await User.create({ username, password, phone })
    // console.log(res.dataValues)
    return res.dataValues //这里是一个psomise对象
  }

  //通过Id更新用户信息
  async updateById({ id, username, password, isAdmin }: adminInfo) {
    const whereOpt = { id }
    const newUser = {}

    username && Object.assign(newUser, { username })
    password && Object.assign(newUser, { password })
    isAdmin && Object.assign(newUser, { isAdmin })

    console.log(newUser, 'newUser')
    const res = await Admin.update(newUser, { where: whereOpt })

    return res[0] > 0 ? true : false
  }

  //通过Id获取用户信息
  async findUserInfoById(id: number) {
    const res = await Admin.findByPk(id, {
      attributes: ['id', 'username', 'avatar', 'desc']
    })

    //  return res ? res.dataValues : null
    if (res) {
      return res.dataValues
    } else {
      throw new GetAdminException('')
    }
  }
}

export default new UserService()
